using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text.RegularExpressions;

public static class CodeCleaner : object {
    [MenuItem("Tools/Clean code")]
    public static void Execute() {
        foreach (Object o in Selection.GetFiltered(typeof(MonoScript), SelectionMode.DeepAssets)) {
            if (IsCSharpScript(o)) {
                CleanCode(o as MonoScript);
            }
        }
    }

    private static bool IsCSharpScript(Object o) {
        return (AssetDatabase.GetAssetPath(o).EndsWith(".cs"));
    }

    private static void CleanCode(MonoScript script) {
        string path = AssetDatabase.GetAssetPath(script);
        Debug.Log("Checking: " + path);
        string[] lines = File.ReadAllLines(path);
        bool modified = false;
        for (int k = 0; k < lines.Length; ++k) {
            string line = lines[k];
            string oldLine = line;
            line = ConvertTabsIntoSpaces(line);
            line = RemoveTrailingSpaces(line);
            if (oldLine != line) {
                modified = true;
                lines[k] = line;
            }
        }
        if (modified) {
            Debug.LogWarning("Modifying: " + path);
            File.WriteAllLines(path, lines);
            AssetDatabase.Refresh();
        }
    }

    private static string ConvertTabsIntoSpaces(string line) {
        return Regex.Replace(line, @"\t", "    ");
    }

    private static string RemoveTrailingSpaces(string line) {
        return Regex.Replace(line, @"\s+$", string.Empty);
    }
}
